package com.qf.servlet;

import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.util.MyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author 孙亚梅
 * @version V1.0
 * @Project bookApp-homework
 * @Package ${PACKAGE_NAME}
 * @Description: ${TODO}
 * @Date 2022/5/14 16:25
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决中午乱码问题
        request.setCharacterEncoding("utf-8");

        //获取前端传入的参数
        String uname = request.getParameter("uname");
        String pwd = request.getParameter("pwd");
        String code = request.getParameter("code");

        //从session 中获取保存的验证码
        HttpSession session = request.getSession();
        String validateCode = (String) session.getAttribute("validateCode");

        //先判断验证码
        if (MyUtil.isEmpty(validateCode)) {
            //重定向登录页面
            response.sendRedirect(request.getContextPath() + "/login.html");
            return;
        }
        //判断验证码是否正确
        //判断code我输入的验证码和validateCode系统的是否一致
        //！取反，如果不正确就直接跳出，如果正确执行下一个if
        if (!code.equals(validateCode)) {
            //重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/login.html");
            return;
        }
            //  ||有一个是空就直接返回
            if (MyUtil.isEmpty(uname) || MyUtil.isEmpty(pwd)) {
                response.sendRedirect(request.getContextPath() + "/login.html");
                return ;
            }
            //走登录的逻辑  调用业务层的内容
            UserService service = new UserServiceImpl();
            boolean result = service.login(uname, pwd);

            if (result) {
                session.setAttribute("uname", uname);
                //登录成功
                response.sendRedirect(request.getContextPath() + "/bookList");

            } else {
                //登录失败
                response.sendRedirect(request.getContextPath() + "/login.html");
            }
        }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
    }
}
